<template>
  <div class="schedule-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的课表</span>
        </div>
      </template>
      <el-table :data="scheduleData" border :span-method="objectSpanMethod">
        <el-table-column prop="section" label="节次" width="80" />
        <el-table-column
          v-for="(day, index) in days"
          :key="index"
          :label="day"
          :prop="'day' + (index + 1)"
        >
          <template #default="{ row }">
            <div v-if="row['day' + (index + 1)]">
              <p>{{ row['day' + (index + 1)].course_name }}</p>
              <p>{{ row['day' + (index + 1)].teacher_name }}</p>
              <p>{{ row['day' + (index + 1)].course_location }}</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getStudentScheduleAPI } from '@/api/student/schedule.js'

const days = ['星期一', '星期二', '星期三', '星期四', '星期五']
const scheduleData = ref([])

const processScheduleData = (data) => {
  const table = Array.from({ length: 10 }, (_, i) => ({
    section: `第${i + 1}节`
  }))

  data.forEach((course) => {
    const [day, start, duration] = course.course_time.split('-').map(Number)
    for (let i = 0; i < duration; i++) {
      const sectionIndex = start + i
      if (sectionIndex < 10) {
        if (!table[sectionIndex]) {
          table[sectionIndex] = { section: `第${sectionIndex + 1}节` }
        }
        table[sectionIndex]['day' + day] = { ...course, isStart: i === 0, duration }
      }
    }
  })
  scheduleData.value = table
}

const fetchSchedule = async () => {
  const { data } = await getStudentScheduleAPI()
  if (data.status === 200) {
    processScheduleData(data.data)
  }
}

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex > 0) {
    const course = row[column.property]
    if (course && course.isStart) {
      return {
        rowspan: course.duration,
        colspan: 1
      }
    } else if (course && !course.isStart) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

onMounted(fetchSchedule)
</script>

<style lang="scss" scoped>
.schedule-container {
  padding: 20px;
}
.el-table p {
  margin: 0;
  line-height: 1.5;
}
</style>
